package com.android.thought.badboys.Sms;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.app.Application;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Scroller;
import android.widget.TextView;

import com.android.thought.badboys.BadBoysApplication;
import com.android.thought.badboys.Model;
import com.android.thought.badboys.R;
import com.android.thought.badboys.Action.IBackupAccessAction;
import com.android.thought.badboys.Common.Const;
import com.android.thought.badboys.Info.DataConversion;
import com.android.thought.badboys.Info.ListBackup;
import com.android.thought.badboys.Info.MessageInfo;
import com.android.thought.badboys.Info.MessageInfo.MESSAGE_TYPE;

public class SmsActivity extends Activity implements View.OnClickListener {
	
	Calendar mCalendar = Calendar.getInstance();
	ListView mListView_Sms;
	SmsAdapter mAdapter_Sms;

	Button mBtn_sms_all = null;
	Button mBtn_sms_out = null;
	Button mBtn_sms_in = null;
	
	View mSelectView = null;

	/**
	 * 불러오기 타입 
	 * 0 전체 // 1 수신  // 2 발신
	 */
	int mLoadtype = 0;
	
	Model mModel = null;

	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);

		setContentView(R.layout.sms_layer);

		this.mBtn_sms_all = (Button) this.findViewById(R.id.btn_sms_all);
		this.mBtn_sms_in = (Button) this.findViewById(R.id.btn_sms_in);
		this.mBtn_sms_out = (Button) this.findViewById(R.id.btn_sms_out);
		
		this.mBtn_sms_all.setOnClickListener(this);
		this.mBtn_sms_in.setOnClickListener(this);
		this.mBtn_sms_out.setOnClickListener(this);
		
		this.mListView_Sms = (ListView) this.findViewById(R.id.listview_sms);
		
		onSelectViewChecking(this.mBtn_sms_all);
		onLoadData(0);
	}
	
	void onLoadData(int type)  {
		this.mLoadtype = type;
		
		if ( mModel == null ) {
			Application app = getApplication();
			
			if (app!= null && app instanceof BadBoysApplication )
				this.mModel = ((BadBoysApplication)app).getModel();	
		}
		
		if ( mModel != null ) { 
			this.mModel.getBackUpInfo(this, new IBackupAccessAction() {
				
				@Override
				public void onSaveComplated(boolean isSucess) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onLoadComplated(ListBackup backup) {
					
					
					final int in = backup.getData().size();

					if ( in > 0 )
					if (mListView_Sms != null) {
						ArrayList<DataConversion> dataConversion =  backup.getData();
						final ArrayList<MessageInfo>  totla = new ArrayList<MessageInfo>();
						
						if ( mLoadtype == 0 ) { 
							for (DataConversion conversion : dataConversion) {
								final ArrayList<MessageInfo> messageAll = conversion.getMessageGroupInfo();
								totla.addAll(messageAll);
							} 
						} else {
							for (DataConversion conversion : dataConversion) {
								final ArrayList<MessageInfo> messageAll = conversion.getMessageGroupInfo();
								
								for ( MessageInfo messageInfo : messageAll ) {
									if (messageInfo.getType() == mLoadtype )
										totla.add(messageInfo);
								}
							} 
						}
						
						Collections.sort(totla, new MessageInfo());
						
						
						if (mAdapter_Sms == null) {
							mAdapter_Sms = new SmsAdapter(SmsActivity.this, totla);
							mListView_Sms.setAdapter(mAdapter_Sms);
						} else {
							mAdapter_Sms.notifyDataSetChanged(totla);
						}
					}

					
				}
			}, true);
		}
	}

	@Override
	public void onClick(View v) {
		final int id = v.getId();
		
		if ( mSelectView != null )
			mSelectView.setSelected(false);
		
		if ( id == R.id.btn_sms_all ) {
			onLoadData(0);
		} else if (id ==R.id.btn_sms_in) {
			onLoadData(1);
		} else if ( id == R.id.btn_sms_out ) {
			onLoadData(2);
		}
		
		onSelectViewChecking(v);
	}
	
	void onSelectViewChecking(View v) { 
		mSelectView = v;
		mSelectView.setSelected(true);
	}

	public class SmsAdapter extends BaseAdapter implements OnClickListener {
		private Context mContext;
		ArrayList<MessageInfo> mList = null;

		
		Calendar mCalendar;

		public SmsAdapter(Context context, List<MessageInfo> list) {
			mContext = context;
			mList = (ArrayList<MessageInfo>) list;

			mCalendar = Calendar.getInstance();
		}

		public int getCount() {
			return mList.size();
		}

		public MessageInfo getItem(int position) {
			return mList.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		@Override
		public void notifyDataSetChanged() {

			super.notifyDataSetChanged();
		}

		public void notifyDataSetChanged(ArrayList<MessageInfo> list) {

			mList = list;
			super.notifyDataSetChanged();
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view;
			Warrper warrper = null;
			if (convertView == null) {
				view = LayoutInflater.from(mContext).inflate(R.layout.call_row, null);
			} else {
				view = (View) convertView;
			}
			

			Object obj = view.getTag();
			
			if ( obj == null || ! (obj instanceof Warrper) ) {
				warrper = new Warrper(view);
				view.setTag(warrper);
			} else { 
				warrper = (Warrper) obj;
			}

			final TextView textview_name = warrper.getTextview_Name();
			final TextView textview_date = warrper.getTextview_Date();
			final View pView = warrper.getPView();
			
			final MessageInfo info = getItem(position);
			
			/**
			 * 1 : 수신  2: 발신
			 */
			int type = info.getType();
			int bgRegId = R.drawable.selector_btn_defult;
			
			if ( type == 1 )
				bgRegId = R.drawable.selector_btn_in_bg;
			else if ( type == 2)
				bgRegId = R.drawable.selector_btn_out_bg;
				
			
			view.setBackgroundResource(bgRegId);

			final String name = info.getNumber();
			final long date = info.getDate();

			mCalendar.setTimeInMillis(date);
			textview_name.setText(name);
			textview_date.setText(Const.sDateFormat.format(mCalendar.getTime()));

			pView.setTag(R.id.ids_item_tag, info);
			pView.setOnClickListener(this);			
			
			return view;
		}

		@Override
		public void onClick(View v) {
			Object ojb = v.getTag(R.id.ids_item_tag);
			
			if ( ojb != null && ojb instanceof MessageInfo ) { 
				final MessageInfo info = (MessageInfo)ojb;
				
				final Dialog dialog = new Dialog(SmsActivity.this, android.R.style.Theme_Black_NoTitleBar);
				dialog.setContentView(R.layout.sms_dialog);
				
				
				
				final Window window =  dialog.getWindow();
				
				WindowManager.LayoutParams lp = (WindowManager.LayoutParams) window.getAttributes();
				
				int full_width = getResources().getDisplayMetrics().widthPixels;
				int full_height = getResources().getDisplayMetrics().heightPixels;
				
				lp.width = (int) (full_width * 0.8);
				lp.height = //WindowManager.LayoutParams.WRAP_CONTENT;
						(int) (full_height * 0.6);
				window.setAttributes(lp);
				
				((TextView)dialog.findViewById(R.id.textview_sms_dialog_name)).setText("전송 번호 : "+ info.getNumber());
				
				mCalendar.setTimeInMillis(info.getDate());				
				
				((TextView)dialog.findViewById(R.id.textview_sms_dialog_time)).setText("전송 날짜 : "+ Const.sDateFormat.format(mCalendar.getTime()));
				
				final LinearLayout linearImage= (LinearLayout) dialog.findViewById(R.id.linear__sms_dialog_image);
				TextView textMessage = (TextView)dialog.findViewById(R.id.textview_sms_dialog_message);
				
				MESSAGE_TYPE type =  info.getMessageType();

				textMessage.setText(info.getBody());
				
				dialog.findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						if ( dialog != null )
							dialog.dismiss();
					
						
						if ( linearImage != null )  {
							int count = linearImage.getChildCount();
							
							for ( int indexCount =0; indexCount < count; indexCount++) { 
								View views =  linearImage.getChildAt(indexCount);
								if (views instanceof ImageView) {
									ImageView imageview = (ImageView) views;
									Drawable d = imageview.getDrawable();
									if ( d != null ) 
										d.setCallback(null);
									
									if  ( d instanceof BitmapDrawable ) 
											((BitmapDrawable) d).getBitmap().recycle();
										
									imageview.setImageDrawable(null);
								}
							}
						}
					}
				});

				
				if ( type.equals(MESSAGE_TYPE.MMS_TEXT) || type.equals(MESSAGE_TYPE.SMS)) { 
					linearImage.setVisibility(View.GONE);
				} else if (type.equals(MESSAGE_TYPE.MMS_MIX) || type.equals(MESSAGE_TYPE.MMS_IMAGE))  {
					linearImage.setVisibility(View.VISIBLE);
					
					if ( type.equals(MESSAGE_TYPE.MMS_IMAGE) ) 
						textMessage.setVisibility(View.GONE);
					
					ArrayList<byte[]> bitmapData = info.getBitMap();
					BitmapFactory.Options option = new Options();

					for (byte[] bs : bitmapData) {
						Bitmap map = BitmapFactory.decodeByteArray(bs, 0	, bs.length, option);
						
						ImageView imageView = new ImageView(mContext);
						
						imageView.setImageBitmap(map);
						
						LinearLayout.LayoutParams param = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
						
						linearImage.addView(imageView, param);
						
						
					}
				}				
				
				dialog.show();
			}
		}
	}
	
	class Warrper {
		View mPview = null;
		TextView mTextview_name= null;
		TextView mTextview_date = null;
		
		public Warrper(View view) {
			this.mPview = view.findViewById(R.id.linear_call_row_p);
			this.mTextview_date= (TextView) view.findViewById(R.id.textview_call_date);
			this.mTextview_name= (TextView) view.findViewById(R.id.textview_call_name);
		}
		
		public View getPView(){
			return this.mPview;
		}
		
		public TextView getTextview_Name() { 
			return this.mTextview_name;
		}
		public TextView getTextview_Date() { 
			return this.mTextview_date;
		}
	}
	
}
